package cn.xuqiudong.rpc.protocol.netty.handler;

import cn.xuqiudong.rpc.common.model.XqdResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.xuqiudong.rpc.protocol.netty.RequestHolder;
import cn.xuqiudong.rpc.protocol.netty.model.NettyProtocolData;
import cn.xuqiudong.rpc.protocol.netty.model.XqdFuture;

/**
 * 描述:netty客户端的处理器
 * @author Vic.xu
 * @date 2022-02-18 11:19
 */
public class XqdNettyClientHandler extends SimpleChannelInboundHandler<NettyProtocolData<XqdResponse>> {

    private static Logger logger = LoggerFactory.getLogger(XqdNettyClientHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, NettyProtocolData<XqdResponse> msg) throws Exception {
        logger.info("接收到服务端的处理结果：{}", new ObjectMapper().writeValueAsString(msg));
        long requestId = msg.getHeader().getRequestId();

        XqdFuture<XqdResponse> future = RequestHolder.REQUEST_MAP.remove(requestId);
        if (future == null) {
            logger.info(requestId + "  对应的future 不存在");
            return;
        }
        //返回结果
        future.getPromise().setSuccess(msg.getBody());
    }
}
